package nl.utwente.ewi.hmi.multitouch.drivers.calibrate;

import java.awt.Dimension;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;

import nl.utwente.ewi.hmi.multitouch.TouchDevice;

public class FixedTransformCalibrator implements TouchDeviceCalibrator {

	private Rectangle2D targetArea = null;

	private static final Rectangle2D UNIT_SQUARE = new Rectangle2D.Float(-1, -1, 2, 2);
	
	public FixedTransformCalibrator(Rectangle2D targetArea) {
		this.targetArea = targetArea;
	}

	public static FixedTransformCalibrator getUnitSquareFixedTransformCalibrator() {
		return new FixedTransformCalibrator(UNIT_SQUARE);
	}

	@Override
	public AffineTransform calibrate(TouchDevice device) {
		Dimension dimension = device.getTouchDeviceInfo().getSize();
		Rectangle2D sourceArea = new Rectangle2D.Float(0, 0, (float)dimension.getWidth(), (float)dimension.getHeight());
		
		AffineTransform transform = new AffineTransform();
		
		double scaleX = targetArea.getWidth() / sourceArea.getWidth();
		double scaleY = targetArea.getHeight() / sourceArea.getHeight();
		// revert to 0,0 origin
		transform.translate(-sourceArea.getX(), -sourceArea.getY());
		transform.scale(scaleX, scaleY);
		
		// correct to target area origin
		transform.translate(targetArea.getX() / scaleX, targetArea.getY() / scaleY);
		

		return transform;
	}
	
}
